package cn.hicard.risk.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;

import cn.hicard.core.CoreDao;

public class BaseDao<T> extends CoreDao<T>{
	
	public BaseDao(){}

	public BaseDao(Class<T> clsT){
		super(clsT);
	}

	/**
	 * 便于注入Spring注解注入sessionFactory
	 * @param sessionFactory
	 */
	@Autowired
	public void setSessionFactoryOverride(SessionFactory sessionFactory){
		super.setSessionFactory(sessionFactory);
	}
	
	/**
	 * 更新实体集合，请注意，集合中的每一个实体T的主键必须存在<br/>
	 * 重写CoreDao中的update方法，这里添加与spring配置中相应的批量处理
	 * @param entities
	 * @throws Exception
	 */
	public void update(final List<T> entities) throws Exception{
		getHibernateTemplate().execute(new HibernateCallback<T>() {
			@Override
			public T doInHibernate(Session session) throws HibernateException,
					SQLException {
				for (int i = 0; i < entities.size(); i++) {
					session.update(entities.get(i));
					if((i+1)%100==0){
						session.flush();
						session.clear();
					}
				}
				return null;
			}
		});
	}
	
	/**
	 * 保存实体集合
	 * 重写CoreDao中的save方法，这里添加与spring配置中相应的批量处理
	 * @param entities
	 * @throws Exception
	 */
	public void save(final List<T> entities) throws Exception{
		getHibernateTemplate().execute(new HibernateCallback<T>() {
			@Override
			public T doInHibernate(Session session) throws HibernateException,
					SQLException {
				for (int i = 0; i < entities.size(); i++) {
					session.save(entities.get(i));
					if((i+1)%100==0){
						session.flush();
						session.clear();
					}
				}
				return null;
			}
		});
	}
}
